#!/bin/bash
if [[ $# -ne 2 ]]; then
    echo "The format is as follows:"
    echo "bash build.sh buildpath installpath"
    echo ":param buildpath: 应用构建绝对路径"
    echo ":param installpath: 应用安装绝对路径"
    exit 1
fi

[[ ! "$1" =~ ^/.* || "$1" = "/" ]] &&  echo "请输入正确的构建路径" && exit 1
[[ ! "$2" =~ ^/.* || "$2" = "/" ]] &&  echo "请输入正确的安装路径" && exit 1

create_dir()
{
    local path=$1
    [[ "$path" =~ .*/$ ]] && path=${path%/*}
    if [[ ! -d "$path" && ! -f "$path" ]]; then mkdir -p $path; else path=$path`date "+%y%m%d%H%M%S"` && mkdir -p $path; fi
    echo $path
}

buildpath=$(create_dir $1)
installpath=$(create_dir $2)

yum install -y m4 environment-modules systemd-devel tar xz gcc rsync
source /etc/profile
module purge

set -e
dep_dir="dependency"
bash $dep_dir/bisheng-compiler-2.1.0.sh $buildpath $installpath
module use $installpath/bisheng-compiler-2.1.0
module load $installpath/bisheng-compiler-2.1.0/bisheng_modulefiles

bash $dep_dir/nim-0.18.0.sh $buildpath $installpath
module use $installpath/nim-0.18.0
module load $installpath/nim-0.18.0/nim_modulefiles


bash $dep_dir/Anaconda3.sh $buildpath $installpath
module use $installpath/Anaconda3
module load $installpath/Anaconda3/anaconda3_modulefiles
source activate python27 

bash falcon-v0.3.0.sh $buildpath $installpath
module use $installpath/FALCON-master/FALCON-integrate/fc_env/
module load $installpath/FALCON-master/FALCON-integrate/fc_env/falcon_modulefiles

mkdir -p pkg/falcon-v0.3.0-hpc && cp -r $installpath/* pkg/falcon-v0.3.0-hpc/

echo "#!/bin/bash" >> pkg/falcon-v0.3.0-hpc/Anaconda3_dir.sh
echo export Anaconda3_dir=$installpath >> pkg/falcon-v0.3.0-hpc/Anaconda3_dir.sh

cat>"pkg/falcon-v0.3.0-hpc/run.sh"<<EOF
#!/bin/bash
yum install -y m4 environment-modules systemd-devel csh time patch libatomic perl-Data-Dumper \\
autoconf automake libtool numactl binutils valgrind flex wget tar libatomic gcc-c++ git
source /etc/profile &> /dev/null 
current_dir="\$(cd "\$(dirname "\${BASH_SOURCE[0]}")" && pwd -P)"

for f in "\${current_dir}"/*; do
  if [[ -d "\${f}" && -f "\$(ls "\${f}"/*modulefiles 2>&1)" ]]; then
    module use "\${f}" && module load "\${f}"/*modulefiles
  fi
done

module use \$current_dir/FALCON-master/FALCON-integrate/fc_env/
module load \$current_dir/FALCON-master/FALCON-integrate/fc_env/falcon_modulefiles

##创建编译时Anaconda路径及Anaconda环境
source Anaconda3_dir.sh
if [[ -d \$Anaconda3_dir ]]; then
   rm -rf \$Anaconda3_dir
fi
mkdir -p \$Anaconda3_dir
cp -r Anaconda3 \$Anaconda3_dir
echo "激活Anaconda环境成功"

source activate python27
echo "激活python环境成功"

cd \$(pwd)/FALCON-master/FALCON-integrate
make init
source env.sh 
make config-edit-user
make all
cd -
echo "激活FALCON环境成功"

EOF
cd pkg/ && tar zcvf falcon-v0.3.0-hpc.tar.gz falcon-v0.3.0-hpc

rm -rf $buildpath
